package com.common.android.utils.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import android.util.Log;

/**
 * @author caimk
 * 
 *         这个类用来实现对线程池的统一管理,除非特殊情况，不然不要直接用使用NdThreadPoolExecutor类去生成线程池
 *         单独生成的线程池必须要在注销或者切换帐号的时候去销毁，并在再次启动
 * 
 */
public class NdExecutors {
	private static NdExecutorService mNdExecutorService;
	private static final ReadWriteLock mLock = new ReentrantReadWriteLock();
	private static final Object quitNotifier = new Object();
	private static NdExecutorService mLastNdExecutorService;
	static {
		mNdExecutorService = new NdExecutorService();
	}

	public void init() {
		mLock.writeLock().lock();
		try {
			if (mNdExecutorService == null) {
				mNdExecutorService = new NdExecutorService();
			}
		} finally {
			mLock.writeLock().unlock();
		}
	}

	public static ExecutorService getCachedThreadPool() {
		mLock.readLock().lock();
		try {
			return mNdExecutorService.getCacheThreadPool();
		} finally {
			mLock.readLock().unlock();
		}
	}

	public static ExecutorService getTinyHttpThreadPool() {
		mLock.readLock().lock();
		try {
			return mNdExecutorService.getTinyHttpThreadPool();
		} finally {
			mLock.readLock().unlock();
		}
	}

	// public static ExecutorService getFileUploadDownloadThreadPool() {
	// mLock.readLock().lock();
	// try {
	// return mNdExecutorService.getFileUploadDownloadThreadPool();
	// } finally {
	// mLock.readLock().unlock();
	// }
	// }

	public static ExecutorService getBackgroundThreadPool() {
		mLock.readLock().lock();
		try {
			Log.d("NdExecutors", "getBackgroundThreadPool mNdExecutorService:" + mNdExecutorService.toString());
			return mNdExecutorService.getBackgroundThreadPool();
		} finally {
			mLock.readLock().unlock();
		}
	}

	// 异步方法退出线程池
	public static void quit() {
		mLock.readLock().lock();
		try {
			Thread t = new Thread() {
				@Override
				public void run() {
					awaitQuit(1000);
				}
			};
			t.setPriority(Thread.MAX_PRIORITY);
			t.start();
		} finally {
			mLock.readLock().unlock();
		}
	}

	/**
	 * 同步方法退出线程池
	 * 
	 * @param timeout
	 */
	public static boolean awaitQuit(long timeout) {
		try {
			mLastNdExecutorService = mNdExecutorService;
			// 生成新的线程池
			mNdExecutorService = new NdExecutorService();
			return mLastNdExecutorService.awaitQuit(timeout);
		} finally {
			synchronized (quitNotifier) {
				quitNotifier.notifyAll();
			}
			mLastNdExecutorService = null;
		}
	}

	public static boolean isQuit() {
		if (mLastNdExecutorService == null) {
			return true;
		}
		return mLastNdExecutorService.isQuit();
	}

	public synchronized static boolean wait4Quit(long timeout) {
		if (isQuit()) {
			return true;
		}
		synchronized (quitNotifier) {
			try {
				quitNotifier.wait(timeout);
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
			}
			return isQuit();
		}
	}
}
